import groovyx.net.http.ContentType
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method
import org.apache.http.HttpEntity
import org.apache.http.entity.mime.MultipartEntityBuilder
import org.cyberneko.html.parsers.SAXParser

def http = new HTTPBuilder("http://lab.ocrking.com")
//.with { it ->
//	it.client.params.setParameter(
//		org.apache.http.conn.params.ConnRoutePNames.DEFAULT_PROXY ,
//		new org.apache.http.HttpHost("127.0.0.1", 8888)
//		)
//	it
//}

def xml

// step 1
http.get path: '/'

// step 2
try {
	http.request(Method.POST) { req ->

		uri.path = '/upload.html'
		requestContentType: "multipart/form-data"
		contentType = ContentType.TEXT

		String sid = delegate.this$0.client.cookieStore.cookies.findResult {
			'SID' == it.name ? it.value : null
		}
		HttpEntity entity = MultipartEntityBuilder.create().setLaxMode()
				.addBinaryBody('Filedata', new File('C:\\Users\\houjinxin\\Desktop\\code\\2.gif'))
				.addTextBody('Filename', '37.png')
				.addTextBody('sid', sid).build()


		req.setEntity(entity)

		response.success = { resp, reader ->

			def str = new StringWriter().with {
				try {
					it << reader
				} catch (ex) {
					// do nothing
				}
				it
			}.toString()
			println str
			if (resp.statusLine.statusCode == 200) {
				def nekoParser = new SAXParser().with {
					setFeature 'http://xml.org/sax/features/namespaces', false
					it
				}
				xml = new XmlParser(nekoParser).parseText(str)
			}
		}
	}
} catch (ex) {
	// do nothing
}

def fileId = xml.depthFirst().FILEID.text()
println "FILEID: $fileId"

// step 3
try {
	http.post path: '/do.html', requestContentType: ContentType.URLENC, contentType: ContentType.TEXT, body: [service: 'OcrKingForCaptcha', language: 'eng', charset: 7, upfile: true, fileID: fileId], { resp, reader ->
		def str = new StringWriter().with {
			try {
				it << reader
			} catch (ex) {
				// do nothing
			}
			it
		}.toString()
		println str
		if (resp.statusLine.statusCode == 200) {
			def nekoParser = new SAXParser().with {
				setFeature 'http://xml.org/sax/features/namespaces', false
				it
			}
			xml = new XmlParser(nekoParser).parseText(str)
		}
	}
} catch (ex) {
	// do nothing
}

println xml.depthFirst().RESULT.text()
println xml.depthFirst().STATUS.text()


